// 增强的交互功能
class EnhancedInteractions {
  constructor() {
    this.messageInput = null;
    this.sendBtn = null;
    this.charCount = null;
    this.isRecording = false;
    this.unreadChatCount = 0;
    this.unreadFlowCount = 0;
    
    this.init();
  }

  init() {
    // 等待DOM加载完成
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => this.setupEnhancedUI());
    } else {
      this.setupEnhancedUI();
    }
  }
  
  // 设置Tab导航
  setupTabNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
      item.addEventListener('click', () => {
        const tabName = item.getAttribute('data-tab');
        if (window.controllerApp) {
          window.controllerApp.switchTab(tabName);
          console.log('切换到标签页:', tabName);
        } else {
          console.error('controllerApp未找到，无法切换标签页');
        }
      });
    });
  }

  setupEnhancedUI() {
    this.messageInput = document.getElementById('messageInput');
    this.sendBtn = document.getElementById('sendBtn');
    this.charCount = document.getElementById('charCount');
    
    if (!this.messageInput || !this.sendBtn || !this.charCount) {
      console.warn('增强交互元素未找到，等待重试...');
      setTimeout(() => this.setupEnhancedUI(), 500);
      return;
    }

    this.setupTextareaAutoResize();
    this.setupCharacterCounter();
    this.setupSendButtonState();
    this.setupQuickActions();
    this.setupTabBadges();
    this.setupConnectionStatus();
    this.setupTypingIndicator();
    this.setupTabNavigation();
    
    console.log('增强交互功能已初始化');
  }

  // 设置文本域自动调整高度
  setupTextareaAutoResize() {
    if (!this.messageInput) return;

    this.messageInput.addEventListener('input', () => {
      // 重置高度以获取正确的scrollHeight
      this.messageInput.style.height = 'auto';
      
      // 设置新高度，限制最大高度
      const maxHeight = 120;
      const newHeight = Math.min(this.messageInput.scrollHeight, maxHeight);
      this.messageInput.style.height = newHeight + 'px';
      
      // 如果内容超过最大高度，显示滚动条
      if (this.messageInput.scrollHeight > maxHeight) {
        this.messageInput.style.overflowY = 'auto';
      } else {
        this.messageInput.style.overflowY = 'hidden';
      }
    });

    // 处理回车键发送消息
    this.messageInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        if (this.messageInput.value.trim() && !this.sendBtn.disabled) {
          this.sendMessage();
        }
      }
    });
  }

  // 设置字符计数器
  setupCharacterCounter() {
    if (!this.messageInput || !this.charCount) return;

    this.messageInput.addEventListener('input', () => {
      const currentLength = this.messageInput.value.length;
      const maxLength = parseInt(this.messageInput.getAttribute('maxlength')) || 500;
      
      this.charCount.textContent = currentLength;
      
      // 根据字符数量改变颜色
      if (currentLength > maxLength * 0.9) {
        this.charCount.style.color = '#ff4444';
      } else if (currentLength > maxLength * 0.7) {
        this.charCount.style.color = '#ffaa00';
      } else {
        this.charCount.style.color = 'rgba(255, 255, 255, 0.4)';
      }
    });
  }

  // 设置发送按钮状态
  setupSendButtonState() {
    if (!this.messageInput || !this.sendBtn) return;

    const updateSendButton = () => {
      const hasText = this.messageInput.value.trim().length > 0;
      this.sendBtn.disabled = !hasText;
      
      if (hasText) {
        this.sendBtn.classList.add('active');
      } else {
        this.sendBtn.classList.remove('active');
      }
    };

    this.messageInput.addEventListener('input', updateSendButton);
    this.messageInput.addEventListener('paste', () => {
      setTimeout(updateSendButton, 10);
    });

    // 初始状态
    updateSendButton();
  }

  // 设置快捷操作按钮
  setupQuickActions() {
    const quickBtns = document.querySelectorAll('.quick-btn');
    
    quickBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        const message = btn.getAttribute('data-message');
        if (message && this.messageInput) {
          this.messageInput.value = message;
          this.messageInput.focus();
          
          // 触发input事件以更新UI状态
          this.messageInput.dispatchEvent(new Event('input'));
          
          // 自动调整高度
          this.messageInput.style.height = 'auto';
          this.messageInput.style.height = this.messageInput.scrollHeight + 'px';
        }
      });
    });
  }

  // 设置Tab徽章
  setupTabBadges() {
    this.updateTabBadge('chat', this.unreadChatCount);
    this.updateTabBadge('flow', this.unreadFlowCount);
  }

  updateTabBadge(tabType, count) {
    const badge = document.getElementById(`${tabType}Badge`);
    if (badge) {
      if (count > 0) {
        badge.textContent = count > 99 ? '99+' : count.toString();
        badge.style.display = 'block';
      } else {
        badge.style.display = 'none';
      }
    }
  }

  // 增加未读消息计数
  incrementUnreadCount(tabType) {
    if (tabType === 'chat') {
      this.unreadChatCount++;
      this.updateTabBadge('chat', this.unreadChatCount);
    } else if (tabType === 'flow') {
      this.unreadFlowCount++;
      this.updateTabBadge('flow', this.unreadFlowCount);
    }
  }

  // 清除未读消息计数
  clearUnreadCount(tabType) {
    if (tabType === 'chat') {
      this.unreadChatCount = 0;
      this.updateTabBadge('chat', 0);
    } else if (tabType === 'flow') {
      this.unreadFlowCount = 0;
      this.updateTabBadge('flow', 0);
    }
  }

  // 设置连接状态
  setupConnectionStatus() {
    this.updateConnectionStatus('online');
  }

  updateConnectionStatus(status) {
    const connectionDot = document.querySelector('.connection-dot');
    const connectionText = document.querySelector('.connection-text');
    
    if (connectionDot && connectionText) {
      connectionDot.className = `connection-dot ${status}`;
      
      switch (status) {
        case 'online':
          connectionText.textContent = '已连接';
          connectionText.style.color = '#4CAF50';
          break;
        case 'offline':
          connectionText.textContent = '已断开';
          connectionText.style.color = '#f44336';
          break;
        case 'connecting':
          connectionText.textContent = '连接中';
          connectionText.style.color = '#ffaa00';
          break;
        default:
          connectionText.textContent = '未知';
          connectionText.style.color = 'rgba(255, 255, 255, 0.6)';
      }
    }
  }

  // 设置打字指示器
  setupTypingIndicator() {
    this.typingIndicator = document.querySelector('.typing-indicator');
  }

  showTypingIndicator() {
    if (this.typingIndicator) {
      this.typingIndicator.style.display = 'flex';
    }
  }

  hideTypingIndicator() {
    if (this.typingIndicator) {
      this.typingIndicator.style.display = 'none';
    }
  }

  // 发送消息
  sendMessage() {
    if (!this.messageInput || !this.messageInput.value.trim()) return;

    const message = this.messageInput.value.trim();
    
    // 触发原有的发送逻辑
    if (window.controllerApp && typeof window.controllerApp.sendChatMessage === 'function') {
      // 清空输入框
      this.messageInput.value = '';
      this.messageInput.style.height = 'auto';
      
      // 更新UI状态
      this.messageInput.dispatchEvent(new Event('input'));
      
      // 调用原有发送方法
      window.controllerApp.sendChatMessage();
    } else {
      console.warn('ControllerApp未找到或sendChatMessage方法不存在');
    }
  }

  // 表情按钮功能
  setupEmojiButton() {
    const emojiBtn = document.getElementById('emojiBtn');
    if (emojiBtn) {
      emojiBtn.addEventListener('click', () => {
        // 这里可以添加表情选择器的逻辑
        console.log('表情按钮被点击');
        // 暂时添加一个简单的表情到输入框
        if (this.messageInput) {
          this.messageInput.value += '😊';
          this.messageInput.dispatchEvent(new Event('input'));
          this.messageInput.focus();
        }
      });
    }
  }

  // 语音录制增强
  enhanceMicButton() {
    const micButton = document.getElementById('micButton');
    const micWaves = document.querySelector('.mic-waves');
    
    if (micButton && micWaves) {
      // 添加长按提示
      let pressTimer = null;
      
      const startPress = () => {
        pressTimer = setTimeout(() => {
          this.showRecordingHint();
        }, 100);
      };
      
      const endPress = () => {
        if (pressTimer) {
          clearTimeout(pressTimer);
          pressTimer = null;
        }
        this.hideRecordingHint();
      };

      micButton.addEventListener('mousedown', startPress);
      micButton.addEventListener('mouseup', endPress);
      micButton.addEventListener('mouseleave', endPress);
      micButton.addEventListener('touchstart', startPress);
      micButton.addEventListener('touchend', endPress);
    }
  }

  showRecordingHint() {
    // 显示录制提示
    const hint = document.createElement('div');
    hint.className = 'recording-hint';
    hint.textContent = '松开结束录音';
    hint.style.cssText = `
      position: absolute;
      bottom: 80px;
      left: 50%;
      transform: translateX(-50%);
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 8px 16px;
      border-radius: 20px;
      font-size: 12px;
      white-space: nowrap;
      z-index: 1000;
      animation: fadeIn 0.3s ease;
    `;
    
    document.body.appendChild(hint);
    this.recordingHint = hint;
  }

  hideRecordingHint() {
    if (this.recordingHint) {
      this.recordingHint.remove();
      this.recordingHint = null;
    }
  }

  // 消息动画增强
  animateNewMessage(messageElement) {
    if (!messageElement) return;
    
    messageElement.style.opacity = '0';
    messageElement.style.transform = 'translateY(20px) scale(0.95)';
    
    // 使用requestAnimationFrame确保动画流畅
    requestAnimationFrame(() => {
      messageElement.style.transition = 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)';
      messageElement.style.opacity = '1';
      messageElement.style.transform = 'translateY(0) scale(1)';
    });
  }

  // 滚动到底部增强
  smoothScrollToBottom() {
    const chatMessages = document.getElementById('chatMessages');
    if (chatMessages) {
      chatMessages.scrollTo({
        top: chatMessages.scrollHeight,
        behavior: 'smooth'
      });
    }
  }

  // 清理资源
  destroy() {
    if (this.recordingHint) {
      this.recordingHint.remove();
    }
    
    // 移除事件监听器
    if (this.messageInput) {
      this.messageInput.removeEventListener('input', this.setupTextareaAutoResize);
      this.messageInput.removeEventListener('keydown', this.setupTextareaAutoResize);
    }
  }
}

// 创建全局实例
window.enhancedInteractions = new EnhancedInteractions();

// 导出类以供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
  module.exports = EnhancedInteractions;
}